//Random number generator in the range [-1,1]
float randomNumberGenerator(int x, int y){
	int n = (int)(x * 40.0 + y * 6400.0);
	n = (n << 13) ^ n;
	return 1.0f - (float)( (n * (n * n * 15731 + 789221) + 1376312589) & 0x7fffffff) / 1073741824.0f;
}

kernel void snowInit(	global float4 *vertices,
						int area_size_x,
						int area_size_z,
						int vertices_mesh_width) {

    unsigned int x = get_global_id(0);
    unsigned int y = get_global_id(1);
    
    int numAgents = vertices_mesh_width * vertices_mesh_width;
    int particleID = x * y;
    
    if( particleID > numAgents)
    	return;
    	
    particleID = y*vertices_mesh_width + x;
    
    float u = (x % vertices_mesh_width) * (area_size_x / (float) vertices_mesh_width) - area_size_x/2 + 320;
    float v = (y % vertices_mesh_width) * (area_size_z / (float) vertices_mesh_width) - area_size_z/2 + 240;
    float w = 400;
    

    // write output vertex
    vertices[particleID]   = (float4)(u, w , v, 1.0f);

}

kernel void snowUpdate(	global float4* vertices,
						int vertices_mesh_width,
						float dt){
						
	unsigned int x = get_global_id(0);
    unsigned int y = get_global_id(1);
    
    int numAgents = vertices_mesh_width * vertices_mesh_width;
    int particleID = x * y;
    
    if( particleID > numAgents)
    	return;
    	
    particleID = y*vertices_mesh_width + x;
    
    float4 pos = vertices[particleID];
    float rnd = randomNumberGenerator(x,y);
    if(rnd < 0)
    	rnd *= -1;
    pos.y = pos.y - (9.8 * dt + rnd);
    
    if(pos.y < 0)
    	pos.y = 400;
    	
    vertices[particleID] = pos;
}